package com.hundsun.s3.mrs.core.endpoint;

import java.util.HashMap;
import java.util.Map;

import com.hundsun.s3.mrs.core.talker.Talker;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;


/**
 * channel管理器
 * @author chenji23607
 *
 */
public class ChannelManager {
	
	
	private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	
	/**
	 * 交谈者管理器
	 * key为交谈者的描述符
	 * value为通道的ChannelId
	 */
	private static Map<String, ChannelId> talker2channel = new HashMap<String, ChannelId>();
	
	/**
	 * 交谈者管理器
	 * key为通道的ChannelId
	 * value为交谈者的描述符
	 */
	private static Map<ChannelId, String> channel2talker = new HashMap<ChannelId, String>();
	
	public static void addChannel(Channel channel, Talker talker) {
		channelGroup.add(channel);
		String id = talker.getId();
		ChannelId channelId = channel.id();
		talker2channel.put(id, channelId);
		channel2talker.put(channelId, id);
	}
	
	/**
	 * 根据接收人的id查找到Channel
	 * @param receiverId
	 * @return
	 */
	public static Channel find(String receiverId) {
		ChannelId channelId = talker2channel.get(receiverId);
		if(channelId==null) {
			return null;
		}
		return channelGroup.find(channelId);
	}
	
	/**
	 * websocket boss线程开启的端口号
	 */
	private static Integer port;


	public static ChannelGroup getChannelGroup() {
		return channelGroup;
	}


	public static void setChannelGroup(ChannelGroup channelGroup) {
		ChannelManager.channelGroup = channelGroup;
	}


	public static Map<String, ChannelId> getTalker2channel() {
		return talker2channel;
	}


	public static void setTalker2channel(Map<String, ChannelId> talker2channel) {
		ChannelManager.talker2channel = talker2channel;
	}


	public static Map<ChannelId, String> getChannel2talker() {
		return channel2talker;
	}


	public static void setChannel2talker(Map<ChannelId, String> channel2talker) {
		ChannelManager.channel2talker = channel2talker;
	}


	public static Integer getPort() {
		return port;
	}


	public static void setPort(Integer port) {
		ChannelManager.port = port;
	}



	public static void removeChannel(Channel channel) {
		ChannelId channelId = channel.id();
		String talkerId = channel2talker.get(channelId);
		channelGroup.remove(channel);
		channel2talker.remove(channelId);
		talker2channel.remove(talkerId);
	}


}


